/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AdminRespostasGUI.java
 *
 * Created on 15/06/2011, 12:02:03
 */
package cliente.gui;


import br.ufpi.domain.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import util.ProtocoloMensagem;
/**
 *
 * @author aersandersonsoares
 */
public class AdminRespostasGUI extends javax.swing.JFrame {
    
    private Long perguntaId;
    private String hostname;
    private int porta;
    private Pergunta pergunta;
    private String mensagemPergunta;
    private String titulo;
    private ProtocoloMensagem protocoloMensagem;
    
    private ArrayList<Resposta> arrayRespostas;

    /** Creates new form AdminRespostasGUI */
    public AdminRespostasGUI(Long perguntaId, String hostname, int porta, String mensagemPergunta, String titulo) {
        this.perguntaId = perguntaId;
        this.hostname = hostname;
        this.porta = porta;
        this.mensagemPergunta=mensagemPergunta;
        this.titulo = titulo;
        protocoloMensagem = new ProtocoloMensagem();
        initComponents();
        
        taPergunta.setText(mensagemPergunta);
        lTitulo.setText(titulo);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taPergunta = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        lTitulo = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabelaRespostas = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        taResposta = new javax.swing.JTextArea();
        cbListarRespostas = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        taComentarioResposta = new javax.swing.JTextArea();
        bComentarResposta = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        cbStatusResposta = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        lPontuacao = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        lIDResposta = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        lUsuarioResposta = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("ADMINISTRACAO DE RESPOSTAS DAS PERGUNTAS");

        taPergunta.setColumns(20);
        taPergunta.setRows(5);
        jScrollPane1.setViewportView(taPergunta);

        jLabel2.setText("Pergunta: ");

        lTitulo.setText("Titulo blablablablablablabla");

        jLabel3.setText("Respostas:");

        tabelaRespostas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Usuario", "Resposta", "Pontuacao"
            }
        ));
        tabelaRespostas.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaRespostasMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tabelaRespostas);

        taResposta.setColumns(20);
        taResposta.setRows(5);
        taResposta.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                taRespostaMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(taResposta);

        cbListarRespostas.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todas as respostas", "Respostas Corretas", "Respostas Parcialmente Corretas", "Nao avaliadas", "Incorretas/Rejeitadas" }));

        jLabel4.setText("Comente sobre esta resposta. Apenas o aluno que a respondeu irá ver o comentario.");

        taComentarioResposta.setColumns(20);
        taComentarioResposta.setRows(5);
        jScrollPane4.setViewportView(taComentarioResposta);

        bComentarResposta.setText("Comentar/Atualizar Comentario");
        bComentarResposta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bComentarRespostaActionPerformed(evt);
            }
        });

        jLabel5.setText("Avaliar resposta como:");

        cbStatusResposta.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Correta", "Parcialmente correta", "Incorreta" }));

        jLabel6.setText("Atribuir pontuacao a resposta:");

        lPontuacao.setText("0.0");

        jButton1.setText("Efetuar alteracoes");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Fechar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel7.setText("Resposta ID:");

        jLabel9.setText("Enviada por:");

        lUsuarioResposta.setText(" ");

        jButton3.setText("Listar respostas");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel1)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                            .add(jLabel2)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(lTitulo, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .add(layout.createSequentialGroup()
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(layout.createSequentialGroup()
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 359, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                        .add(layout.createSequentialGroup()
                                            .add(jLabel5)
                                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                            .add(cbStatusResposta, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 218, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                        .add(layout.createSequentialGroup()
                                            .add(jLabel3)
                                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                            .add(cbListarRespostas, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 200, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .add(jButton3)))
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                        .add(layout.createSequentialGroup()
                                            .add(jLabel7)
                                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                            .add(lIDResposta, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 38, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                            .add(jLabel9)
                                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                            .add(lUsuarioResposta, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 158, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                        .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 386, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                                .add(layout.createSequentialGroup()
                                    .add(jLabel6)
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                    .add(lPontuacao, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 57, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(jButton1))
                            .add(10, 10, 10))
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 760, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jLabel4)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(jButton2)
                        .add(jScrollPane4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 744, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(bComentarResposta))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(lTitulo))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 52, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(cbListarRespostas, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 148, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel5)
                            .add(cbStatusResposta, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel7)
                            .add(lIDResposta, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 17, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                .add(jLabel9)
                                .add(lUsuarioResposta)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 148, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel6)
                    .add(lPontuacao, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel4)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(bComentarResposta)
                .add(32, 32, 32)
                .add(jButton2)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tabelaRespostasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaRespostasMouseClicked
        // TODO add your handling code here:

        int selecionado = tabelaRespostas.getSelectedRow();
        Resposta r = arrayRespostas.get(selecionado);

        if(r.getComentario().equals("") || r.getComentario() == null)
            taComentarioResposta.setText(r.getComentario());
        taResposta.setText(r.getMensagem());
        lIDResposta.setText(""+r.getId());
        lUsuarioResposta.setText(r.getUsuario().getNomeCompleto());
        lPontuacao.setText(""+r.getPontuacao());
        
        int status = r.getStatus();
        switch(status) {
            case 2: //Corretas
                System.out.println("Correta");
                cbStatusResposta.setSelectedIndex(0);
                break;
            case 1: //Parcialmente corretas
                System.out.println("PCorreta");
                cbStatusResposta.setSelectedIndex(1);
                break;
            case 3: //Incorretas
                System.out.println("INCorreta");
                cbStatusResposta.setSelectedIndex(2);
                break;
        }
    }//GEN-LAST:event_tabelaRespostasMouseClicked

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void bComentarRespostaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bComentarRespostaActionPerformed
        // TODO add your handling code here:
        if(lIDResposta.getText().isEmpty())
            mostrarMensagem("Erro: Selecione uma pergunta primeiro");
        else {
            Long id = Long.parseLong(lIDResposta.getText());
            String comentario = taComentarioResposta.getText();
            String[] mensagemRecebida = protocoloMensagem.decodificar(this.enviarReceberPergunta(protocoloMensagem.adminCodificarComentarResposta(id, comentario)));
            // Se retornar sucesso mostrar mensagem que foi atualizado...
            if(mensagemRecebida[0].equals("SUCE"))
                mostrarMensagem(mensagemRecebida[1]);
            else
                mostrarMensagem("Erro comentar resposta"); 
            // Senao informar erro.
        }
    }//GEN-LAST:event_bComentarRespostaActionPerformed

    private void taRespostaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_taRespostaMouseClicked
        // TODO add your handling code here:
        
    }//GEN-LAST:event_taRespostaMouseClicked

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        try {
            int selecionado = cbListarRespostas.getSelectedIndex();
            arrayRespostas = protocoloMensagem.adminDecodificarRespostas(this.enviarReceberPergunta(
                    protocoloMensagem.adminCodificarPedidoRespostas(perguntaId, 0)));
            if(arrayRespostas != null) {
                DefaultTableModel modelo = (DefaultTableModel) tabelaRespostas.getModel();
                //Limpar tabela...
                modelo.fireTableRowsDeleted(0, modelo.getRowCount());
                for (int i = modelo.getRowCount(); i > 0; i--) {
                    modelo.removeRow(0);
                }
                
                //Popular tabela com o arraylist perguntas..
                Iterator<Resposta> it = arrayRespostas.iterator();
                while(it.hasNext()) {
                    Resposta p = (Resposta) it.next();

                    Vector vetor = new Vector();
                    vetor.add(p.getUsuario().getNomeCompleto());
                    vetor.add(p.getMensagem());
                    vetor.add(p.getPontuacao());
                    
                    modelo.addRow(vetor);
                }
            }
        } catch(Exception e) {
            System.out.println("Erro ao listar as respostas, tente novamente");
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        if(lIDResposta.getText().isEmpty())
            mostrarMensagem("Erro: Selecione uma pergunta primeiro");
        else {
            Long respostaId = Long.parseLong(lIDResposta.getText());
            int opcaoSelecionada = cbStatusResposta.getSelectedIndex();
            double nota = 0;
            if(lPontuacao.getText() != null || lPontuacao.getText() != "") {
                nota = Double.parseDouble(lPontuacao.getText());
            }
            String[] mensagemRecebida = protocoloMensagem.decodificar(this.enviarReceberPergunta(protocoloMensagem.adminAtualizarResposta(respostaId, opcaoSelecionada, nota)));
            // Se retornar sucesso mostrar mensagem que foi atualizado...
            if(mensagemRecebida[0].equals("SUCE"))
                mostrarMensagem(mensagemRecebida[1]);
            else
                mostrarMensagem("Erro comentar resposta"); 
            // Senao informar erro.
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void limparCampos() {
        taComentarioResposta.setText("");
        taResposta.setText("");
        lIDResposta.setText("");
        lUsuarioResposta.setText("");
    }
    
    private String enviarReceberPergunta(String mensagem) {

        try {

            Socket clientSocket = new Socket(hostname, porta);
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            DataInputStream inFromServidor = new DataInputStream(clientSocket.getInputStream());
            outToServer.writeUTF(mensagem);
            return inFromServidor.readUTF();
        } catch (java.net.ConnectException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possivel a Conexão com o Servidor");

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new AdminRespostasGUI().setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bComentarResposta;
    private javax.swing.JComboBox cbListarRespostas;
    private javax.swing.JComboBox cbStatusResposta;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JLabel lIDResposta;
    private javax.swing.JTextField lPontuacao;
    private javax.swing.JLabel lTitulo;
    private javax.swing.JLabel lUsuarioResposta;
    private javax.swing.JTextArea taComentarioResposta;
    private javax.swing.JTextArea taPergunta;
    private javax.swing.JTextArea taResposta;
    private javax.swing.JTable tabelaRespostas;
    // End of variables declaration//GEN-END:variables

    private void mostrarMensagem(String string) {
        JOptionPane.showMessageDialog(this,string);
    }
}
